package com.dianzhihan.cashier.controller;

import com.dianzhihan.cashier.model.order.Order;
import com.dianzhihan.cashier.model.product.Product;
import com.dianzhihan.cashier.model.user.User;
import com.dianzhihan.cashier.service.OrderService;
import com.dianzhihan.cashier.service.ProductService;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Dianzhi Han
 * @version 1.0
 * @description: Controller类，专门存放Json数据
 * @date 2023/2/9 21:05
 */

@RestController
@Slf4j
public class JsonController {
    private final ProductService productService;
    private final OrderService orderService;

    @Autowired
    public JsonController(ProductService productService, OrderService orderService) {
        this.productService = productService;
        this.orderService = orderService;
    }


    //静态内部类，product的View版本，给别人看的
    @Data
    @Slf4j
    public static class ProductView{

        private String productId; //商品ID
        private String productname;//商品名字
        private String description;//商品介绍
        private int stock;//商品库存
        private String unit;// 商品单位
        private double price;  //显示给前端看的是元，所以double类型
        private int discount;//商品折扣

        public ProductView(Product product) {

            this.productId = String.valueOf(product.getProductId());
            this.productname = product.getProductname();
            this.description = product.getDescription();
            this.stock = product.getStock();
            this.unit = product.getUnit();
            this.price = product.getPrice() / 100.0;    // 必须是 100.0 而不能是 100
            this.discount = product.getDiscount();
            log.debug("ProductView(product = {})", product);
        }

    }


    //商品列表View类
    @Data
    @Slf4j
    public static class ProductListView{
        // JsonInclude.Include.NON_NULL 只有在 不是 null 的时候，才会写到响应中
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private String url;
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private List<ProductView> productViews;

        //成功返回商品列表的View，此时url为空
        public static ProductListView success(List<Product> productList){
            ProductListView productListView = new ProductListView();
//            productListView.productViews = new ArrayList<>();
//            for (Product product: productList) {
//                ProductView productView = new ProductView(product);
//                productListView.productViews.add(productView);
//            }

            // 针对 这个 stream 中的每一项（每一项都是一个 Product 对象）
            // 调用传入的这个方法 Product::new
            // 调用完成之后，每一项 Product 都得到了一个新的 ProductView 对象了
            //最后，再收集成 List<ProductView>
            productListView.productViews = productList.stream()
                    .parallel() // 变成多线程，批量处理
                    .map(ProductView::new)
                    .collect(Collectors.toList());
            return productListView;
        }

        //失败就返回url，此时列表为空
        public static ProductListView failure(String redirectUrl){
            // 注意，这里不是 HTTP 协议层面的重定向，会让前端进行跳转
            ProductListView productListView= new ProductListView();
            productListView.url = redirectUrl;
            return productListView;
        }

    }

    @GetMapping("/product/list.json")
    public ProductListView getProductList(HttpServletRequest request){

        //用户登录检测逻辑
        HttpSession session = request.getSession(false);

        if(session == null){
            //说明没有登录，转到登录逻辑
            return ProductListView.failure("/login.html");
        }

        if (session !=null){
            User currentUser = (User) session.getAttribute("currentUser");
        }

        //获取到商品真实列表
        List<Product> list = productService.getList();


        // 返回商品列表的View版本
        return ProductListView.success(list);

    }

    @Data
    @Slf4j
    public static class OrderView{
        String uuid;
        String orderStatus;
        String creatAt;
        String finishAt;

        public OrderView(Order order){
            this.uuid =order.getUuid();
            this.orderStatus = order.getStatus().toString();
            this.creatAt = String.valueOf(order.getCreatedAt());
            this.finishAt = String.valueOf(order.getFinishedAt());
            if(this.finishAt.equals("null")){
                this.finishAt = "等待支付";
            }
            log.debug("OrderView为{}",order);
        }
    }

    @Data
    public static class OrderListView{
        // JsonInclude.Include.NON_NULL 只有在 不是 null 的时候，才会写到响应中
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private String url;
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private List<OrderView> orderViews;

        public static OrderListView success(List<Order> orderList){
            OrderListView orderListView = new OrderListView();
            orderListView.orderViews =orderList.stream().map(OrderView::new).collect(Collectors.toList());
            return orderListView;
        }

        public static OrderListView failure(String redirectUrl){
            OrderListView orderListView = new OrderListView();
            orderListView.url =redirectUrl;
            return orderListView;
        }


    }

    @GetMapping("/order/list.json")
    public OrderListView orderList(HttpServletRequest request){
        User currentUser = null;
        HttpSession session = request.getSession(false);
        if (session != null) {
            currentUser = (User) session.getAttribute("currentUser");
        }

        if (currentUser == null) {
            // 说明没有登录
            return OrderListView.failure("/login.html");
        }

        List<Order> orderList = orderService.getList();

        return OrderListView.success(orderList);
    }


}
